<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="开始时间" prop="startTime">
        <el-date-picker
          clearable
          v-model="queryParams.startTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择开始时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间" prop="endTime">
        <el-date-picker
          clearable
          v-model="queryParams.endTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择结束时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['business:openingPage:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['business:openingPage:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['business:openingPage:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['business:openingPage:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="openingPageList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="" align="center" prop="id" v-if="true" />
      <el-table-column label="文件类型" align="center" prop="type">
        <template #default="scope">
          <span>{{ scope.row.type === "1" ? "视频" : "图片" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="文件路径" align="center" prop="fileUrl">
        <template #default="scope">
          <video
            controls
            muted
            :width="200"
            :height="200"
            type="video/mp4"
            v-if="scope.row.type === '1'"
            :src="scope.row.fileUrl"
          >
          </video>

          <image-uploads
            v-else
            v-model="scope.row.fileUrl"
            :limit="1"
          ></image-uploads>
        </template>
      </el-table-column>

      <el-table-column label="开启状态" align="center" prop="status">
        <template #default="scope">
          <el-tag
            :type="scope.row.status === '0' ? 'success' : 'danger'"
            disable-transitions
            >{{ scope.row.status === "0" ? "启用" : "停用" }}</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column
        label="开始时间"
        align="center"
        prop="startTime"
        width="180"
      >
        <template #default="scope">
          <div>{{ parseTime(scope.row.startTime, "{y}-{m}-{d}") }}</div>
          <div>{{ parseTime(scope.row.startTime, "{h}:{i}:{s}") }}</div>
        </template>
      </el-table-column>
      <el-table-column
        label="结束时间"
        align="center"
        prop="endTime"
        width="180"
      >
        <template #default="scope">
          <div>{{ parseTime(scope.row.endTime, "{y}-{m}-{d}") }}</div>
          <div>{{ parseTime(scope.row.endTime, "{h}:{i}:{s}") }}</div>
        </template>
      </el-table-column>
      <el-table-column label="开屏停留时间，单位秒" align="center" prop="dwellTime"/>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['business:openingPage:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['business:openingPage:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>

    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改开屏页管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form
        ref="openingPageRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="文件类型" prop="type">
          <el-select
            v-model="form.type"
            placeholder="请选择文件类型"
            @change="handleAddChange"
          >
            <el-option
              v-for="dict in matter_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item
          label="请上传视频"
          prop="fileUrl"
          v-if="isAddType === '1'"
        >
          <!-- <el-input v-model="form.fileUrl" placeholder="请输入文件路径" /> -->
          <video-upload v-model="form.fileUrl"></video-upload>
        </el-form-item>

        <el-form-item label="请上传图片" prop="fileUrl" v-else>
          <!-- <el-input v-model="form.fileUrl" placeholder="请输入文件路径" /> -->
          <image-uploads v-model="form.fileUrl" :limit="1"></image-uploads>
        </el-form-item>

        <el-col :span="14">
          <el-form-item label="跳转类型" prop="linkTpe">
            <el-select v-model="form.linkType" placeholder="请选择" @change="linkTpeChanged">
              <el-option
                v-for="dict in banner_link_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-form-item label="跳转地址" prop="link">
          <!--          <el-input v-model="form.picUrl" type="textarea" placeholder="请输入内容" />-->
          <el-input
            v-if="bannerLinkType === '1' || bannerLinkType === undefined "
            v-model="form.link"
            placeholder="请输入跳转内链"
          />

          <el-input
            v-if="bannerLinkType === '2' "
            v-model="form.link"
            placeholder="请输入跳转外链"
          />
          <image-uploads
            v-if="bannerLinkType === '3'"
            v-model="form.link"
            limit="1">

          </image-uploads>

          <el-input
            v-if="bannerLinkType === '4' "
            v-model="form.link"
            placeholder="请输入文本内容"
          />
        </el-form-item>

        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            clearable
            v-model="form.startTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择开始时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            clearable
            v-model="form.endTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择结束时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="开屏停留时间，单位秒" prop="dwellTime">
          <el-input-number v-model="form.dwellTime" controls-position="right" :min="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm"
            >确 定</el-button
          >
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="OpeningPage">
import {
  listOpeningPage,
  getOpeningPage,
  delOpeningPage,
  addOpeningPage,
  updateOpeningPage,
} from "@/api/business/openingPage";
import { ElMessage } from "element-plus";
import ImageUploads from "@/components/ImageUploads/index.vue";

const { proxy } = getCurrentInstance();
const { matter_type,banner_link_type } = proxy.useDict("matter_type","banner_link_type");

const openingPageList = ref([]);
const open = ref(false);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
//跳转类型判断
const bannerLinkType = ref("1");
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    type: undefined,
    fileUrl: undefined,
    status: undefined,
    startTime: undefined,
    endTime: undefined,
  },
  rules: {
    id: [{ required: true, message: "不能为空", trigger: "blur" }],
    type: [
      {
        required: true,
        message: "文件类型不能为空",
        trigger: "change",
      },
    ],
    fileUrl: [{ required: true, message: "文件路径不能为空", trigger: "blur" }],
    status: [
      {
        required: true,
        message: "开启状态：0 = 开启，2 = 停用不能为空",
        trigger: "change",
      },
    ],
    startTime: [
      { required: true, message: "开始时间不能为空", trigger: "blur" },
    ],
    endTime: [{ required: true, message: "结束时间不能为空", trigger: "blur" }],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询开屏页管理列表 */
function getList() {
  loading.value = true;
  listOpeningPage(queryParams.value).then((response) => {
    response.rows.forEach((item) => {
      item.startDate = new Date(item.startTime).getTime();
      item.endDate = new Date(item.endTime).getTime();
    });

    openingPageList.value = response.rows;
    console.log(openingPageList.value);
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    type: null,
    dwellTime: 0,
    fileUrl: null,
    status: null,
    linkType: "1",
    startTime: null,
    endTime: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    delFlag: null,
  };
  proxy.resetForm("openingPageRef");
}
// const time = ref(form.value.startTime);

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加开屏页管理";
}

const isAddType = ref(0);
// 选择类型
function handleAddChange(item) {
  console.log(item);
  isAddType.value = item;
}

/** 修改按钮操作 */
const id = ref(undefined);
function handleUpdate(row) {
  loading.value = true;
  reset();
  const _id = row.id || ids.value;
  getOpeningPage(_id).then((response) => {
    loading.value = false;
    form.value = response.data;
    open.value = true;
    title.value = "修改开屏页管理";
  });
}

function onTime() {
  console.log(Date.now());

  let nowTime = Date.now(); //当前时间
  let startDate = new Date(form.value.startTime).getTime(); //选择的开始时间
  let endDate = new Date(form.value.endTime).getTime(); // 选择的结束时间

  // if (startDate < nowTime) {
  //   ElMessage({
  //     dangerouslyUseHTMLString: true,
  //     message: "开始时间不能小于当前时间",
  //   });
  //   return true;
  // }
  if (startDate > endDate) {
    ElMessage({
      dangerouslyUseHTMLString: true,
      message: "结束时间不能小于开始时间",
    });
    return true;
  }

  let flag = openingPageList.value.map((item) => {
    console.log(startDate < item.endDate, "--------", endDate > item.startDate);
    if (startDate < item.endDate && endDate > item.startDate) {
      return true;
    } else {
      return false;
    }
  });
  console.log(flag);
  if (flag.some((item) => item)) {
    ElMessage({
      dangerouslyUseHTMLString: true,
      message: "当前时间区间不能与以前的时间区间冲突",
    });
    return true;
  }
}

/** 提交按钮 */
function submitForm() {
  console.log(openingPageList.value);
  proxy.$refs["openingPageRef"].validate((valid) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id != null) {
        // if (onTime("flag")) {
        //   buttonLoading.value = false;
        //   return;
        // }
        updateOpeningPage(form.value)
          .then((response) => {
            proxy.$modal.msgSuccess("修改成功");
            open.value = false;
            getList();
          })
          .finally(() => {
            buttonLoading.value = false;
          });
      } else {
        if (onTime()) {
          buttonLoading.value = false;
          return;
        }
        // return;
        addOpeningPage(form.value)
          .then((response) => {
            proxy.$modal.msgSuccess("新增成功");
            open.value = false;
            getList();
          })
          .finally(() => {
            buttonLoading.value = false;
          });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除开屏页管理编号为"' + _ids + '"的数据项？')
    .then(function () {
      loading.value = true;
      return delOpeningPage(_ids);
    })
    .then(() => {
      loading.value = true;
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {})
    .finally(() => {
      loading.value = false;
    });
}
/* 动态显隐跳转链接类型 */
function linkTpeChanged(e){
  bannerLinkType.value = e
}
/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "business/openingPage/export",
    {
      ...queryParams.value,
    },
    `openingPage_${new Date().getTime()}.xlsx`
  );
}

getList();
</script>
